package com.nchuAo.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.nchuAo.util.PageResult;
import com.nchuAo.entity.Category;
import com.nchuAo.entity.Goods;
import com.nchuAo.mapper.GoodsMapper;
import com.nchuAo.service.CategoryService;
import com.nchuAo.service.GoodsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nchuAo.vo.GoodsVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class GoodsServiceImpl extends ServiceImpl<GoodsMapper, Goods> implements GoodsService {
	@Autowired
	private CategoryService CategoryService;
	// 1. 分页查询
	@Override
	public PageResult<Goods> findByPage(Integer page, Integer pageSize) {
		// 1. 开始分页
		Page<Goods> page1 = this.page(new Page<>(page, pageSize));

		// 2. 封装分页结果
		return new PageResult<>(page1.getRecords(),page1.getTotal());
	}

	// 3. 条件带分页查询
	@Override
	public PageResult<Goods> search(Integer page, Integer pageSize, GoodsVO vo) {
		// 1. 进行分页带条件查询
		// 1.1 封装查询条件
		QueryWrapper<Goods> queryWrapper = new QueryWrapper<>();
		queryWrapper.like(StrUtil.isNotBlank(vo.getSname()), "sname", vo.getSname());
		queryWrapper.eq(vo.getCid() != null && vo.getCid() != 0, "cid", vo.getCid());
		// 1.2 开始分页查询
		Page<Goods> page1 = this.page(new Page<>(page, pageSize), queryWrapper);
		// 1.3 处理商品所在种类名称
		page1.getRecords().forEach(Goods -> {
			Category Category = CategoryService.getById(Goods.getCid());
			Goods.setCname(Category.getCname());
		});
		// 2. 封装分页结果
		return new PageResult<>(page1.getRecords(),page1.getTotal());
	}

	// 添加商品
	@Override
	public boolean add(Goods Goods) {
		return this.save(Goods);
	}
}
